package com.voicechat.firstmet.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.BuyVIPActivity;
import com.voicechat.firstmet.activity.GoldDepositsActivity;
import com.voicechat.firstmet.activity.PostDetailsActivity;
import com.voicechat.firstmet.activity.WebPageActivity;
import com.voicechat.firstmet.bean.CommBean;
import com.voicechat.firstmet.bean.CoummunityNotice;
import com.voicechat.firstmet.bean.PostBean;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.fragment.CommunityFragment;
import com.voicechat.firstmet.fragment.CommunityNewFragment;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.CommunityService;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CircleImageView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import library.banner.layoutmanager.BannerLayout;
import library.banner.layoutmanager.WebBannerAdapter;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.adapter
 * @ClassName: 社区listAdapter
 * @Description: java类作用描述
 * @Author: ljp
 * @CreateDate: 2018/9/4 14:11
 * @Version: 1.0
 */
public class CommunityAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private List<PostBean.PageBean.ListBean> tlist;
    private String TAG = "CommunityAdapter";
    public ItemSetClick itemSetClick;
    private int position1;
    private String flag;
    private int BANNER = -1;
    private int ITEMTYPE = 0;
    private ArrayList<CommBean.MapBean.TimeIntervalBean> timeIntervalBeans;

    /**
     * @param context activity_imessage
     * @param tlist   集合
     * @param mLayout 主布局
     */
    public CommunityAdapter(Context context, List<PostBean.PageBean.ListBean> tlist, int mLayout, String flag) {
        //   super(context, tlist, mLayout);
        this.tlist = tlist;
        this.context = context;
        this.flag = flag;
        timeIntervalBeans = new ArrayList<>();
    }

    public void setTimeIntervalBeans(ArrayList<CommBean.MapBean.TimeIntervalBean> timeIntervalBeans) {
        this.timeIntervalBeans = timeIntervalBeans;
    }

    public List<PostBean.PageBean.ListBean> getTlist() {
        return tlist;
    }


    public void setItemSetClick(ItemSetClick itemSetClick) {
        this.itemSetClick = itemSetClick;
    }


   /* @Override
    protected RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return null;
    }

    @Override
    protected RecyclerView.ViewHolder getItemViewHolder(View view) {
      //  ViewHolder1 viewHolder1 = new ViewHolder1(view);
        return null;
    }*/


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        if (i == BANNER) {
            return new HeadViewHolder(View.inflate(context, R.layout.fragment_list_head, null));
        } else {
            return new ViewHolder1(View.inflate(context, R.layout.item1_community, null));
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        if (viewHolder instanceof HeadViewHolder) {
            HeadViewHolder headViewHolder = (HeadViewHolder) viewHolder;
            WebBannerAdapter webBannerAdapter = new WebBannerAdapter(context, timeIntervalBeans);
            webBannerAdapter.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    CommBean.MapBean.TimeIntervalBean timeIntervalBean = timeIntervalBeans.get(position);
                    Intent intent = null;
                    Uri uri = null;
                  //  Log.i(TAG, "onItemClick: ------"+timeIntervalBean.toString());
                    switch (timeIntervalBean.getRemarks()) {//h5:"1"  金币充值："2"  会员购买："3"  热门帖子："4"
                        case "1":
                            intent = new Intent(context, WebPageActivity.class);
                            intent.putExtra("url", timeIntervalBean.getH5Url());
                            intent.putExtra("userId", CommunityNewFragment.mySeleInfo.getId());
                            intent.putExtra("title", timeIntervalBean.getTitle());
                            context.startActivity(intent);
                            break;
                        case "2":
                            intent = new Intent(context, GoldDepositsActivity.class);
                            context.startActivity(intent);
                          /*  uri = Uri.parse(HTTPAPI.URL_RECHARGE + "id=" + CommunityNewFragment.mySeleInfo.getNumber());
                            intent = new Intent(Intent.ACTION_VIEW, uri);
                            context.startActivity(intent);*/
                            break;
                        case "3":
                            intent = new Intent(context, BuyVIPActivity.class);
                            intent.putExtra("data","");
                            context.startActivity(intent);
                            /*uri = Uri.parse(HTTPAPI.URL_MEMBER + "id=" + CommunityNewFragment.mySeleInfo.getNumber());
                            intent = new Intent(Intent.ACTION_VIEW, uri);
                            context.startActivity(intent);*/
                            break;
                        case "4":
                            setHttpPost(timeIntervalBean.getHotId());
                            break;
                    }
                }
            });
            headViewHolder.bannerList.setAdapter(webBannerAdapter);
            headViewHolder.bannerList.setCenterScale(1.0f);
            headViewHolder.bannerList.setShowIndicator(false);
        } else if (viewHolder instanceof ViewHolder1) {
            //  Log.i(TAG, "onBindViewHolder: ---getItemCount---"+getItemCount());
            String[] strings = new String[9];
            if (tlist != null && tlist.size() != 0) {
                if (flag.equals("cummunity")) {
                    if (position == 2) {
                        return;
                    }
                    if(position >= 3){
                        position = position - 1;
                    }
                }
                //Log.i(TAG, "onBindViewHolder: -----position-----" + position);
                ViewHolder1 viewHolder1 = (ViewHolder1) viewHolder;
                PostBean.PageBean.ListBean listBean = tlist.get(position);
                //Log.i(TAG, "onBindViewHolder: ----------"+listBean.toString());
                if (!TextUtils.isEmpty(listBean.getAvatarUrl())) {
                    if (!listBean.getAvatarUrl().equals(viewHolder1.imageIcon.getTag(R.id.image_icon))) {
                        // 加载图片
                        viewHolder1.imageIcon.setTag(R.id.image_icon, listBean.getAvatarUrl());
                        GlideLoadUtils.getInstance().glideLoad(context, OssConfig.OSS_HTTP + listBean.getAvatarUrl(),
                                viewHolder1.imageIcon);
                        //setImage(listBean.getAvatarUrl(), viewHolder1.imageIcon);
                    }
                }
                //  viewHolder1.tvTitle.setText(listBean.getMdTitle());
                if (!TextUtils.isEmpty(listBean.getVoiceUrl())) {
                    viewHolder1.linearSendVoice.setVisibility(View.VISIBLE);
                    viewHolder1.tvVoiceTime.setText(listBean.getDuration() + "s");
                } else {
                    viewHolder1.linearSendVoice.setVisibility(View.GONE);
                }
                viewHolder1.tvContent.setVisibility(View.VISIBLE);
                viewHolder1.tvContent.setText(listBean.getContent());
                viewHolder1.tvCommNumber.setText(listBean.getDiscussCount() + "");
                viewHolder1.tvLikeNumber.setText(listBean.getFabulousCount() + "");
                if (!TextUtils.isEmpty(listBean.getCreateDate())) {
                    String standardDate = Utils.getStandardDate(listBean.getCreateDate());//将返回时间转换为多久前
                    viewHolder1.tvDate.setText(standardDate);
                }
                if (!TextUtils.isEmpty(listBean.getuType()) && listBean.getuType().equals("2")) {//判断是否是主播
                    viewHolder1.imageIsanchor.setVisibility(View.VISIBLE);
                    GlideLoadUtils.getInstance().glideLoad(context, OssConfig.OSS_HTTP + listBean.getExclusiveUrl(),
                            viewHolder1.imageIsanchor);
                } else {
                    viewHolder1.imageIsanchor.setVisibility(View.GONE);
                }
                PostPictureAdapter pictureAdapter = null;
                //照片
                if (TextUtils.isEmpty(listBean.getUrl())) {
                    viewHolder1.recyclerPostPicture.setVisibility(View.GONE);
                } else {
                    viewHolder1.recyclerPostPicture.setVisibility(View.VISIBLE);
                    strings = Utils.spitPictureUrl(listBean.getUrl());
                    List<String> listImages;
                    if (strings.length > 3) {
                        listImages = Arrays.asList(strings).subList(0, 3);
                    } else {
                        listImages = Arrays.asList(strings);
                    }
                    pictureAdapter = new PostPictureAdapter(context, listImages, R.layout.item_post_picture);
                    GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
                    viewHolder1.recyclerPostPicture.setHasFixedSize(true);
                    viewHolder1.recyclerPostPicture.setLayoutManager(gridLayoutManager);
                    viewHolder1.recyclerPostPicture.setAdapter(pictureAdapter);
                    pictureAdapter.setOnClick(new PostPictureAdapter.OnClick() {
                        @Override
                        public void onSetPictureClick(View view, int position) {
                            itemSetClick.setItemClick(viewHolder1.recyclerPostPicture, listBean);
                        }
                    });
                }
                //Log.i(TAG, "onBindViewHolder: ----position-----"+position+"--listBean.getIsFabulous()--"+listBean.getIsFabulous());
                if (listBean.getIsFabulous().equals("0")) {//我是否点赞  0 未点赞   1 点赞
                    viewHolder1.imageLike.setImageResource(R.mipmap.unlike);
                } else {
                    viewHolder1.imageLike.setImageResource(R.mipmap.like);
                }
                if (!TextUtils.isEmpty(listBean.getvType()) &&
                        listBean.getvType().equals("1")) {//判断是vip等级 1 月 2 年 0 不是会员
                    viewHolder1.imageVip.setVisibility(View.VISIBLE);
                    viewHolder1.imageVip.setImageResource(R.mipmap.vip_month);
                    viewHolder1.tvNikeName.setTextColor(context.getResources().getColor(R.color.colorFF3B5E));
                } else if (listBean.getvType().equals("2")) {
                    viewHolder1.imageVip.setVisibility(View.VISIBLE);
                    viewHolder1.imageVip.setImageResource(R.mipmap.vip_year);
                    viewHolder1.tvNikeName.setTextColor(context.getResources().getColor(R.color.colorFF3B5E));
                } else {
                    viewHolder1.imageVip.setVisibility(View.GONE);
                    viewHolder1.tvNikeName.setTextColor(context.getResources().getColor(R.color.color333333));
                }
                if (listBean.getGender() == 1) {//判断性别  1男 2女
                    viewHolder1.imageSex.setImageResource(R.mipmap.boy);
                    viewHolder1.linearSexAge.setBackgroundResource(R.mipmap.sex_blue);
                } else if (listBean.getGender() == 2) {
                    viewHolder1.imageSex.setImageResource(R.mipmap.girl);
                    viewHolder1.linearSexAge.setBackgroundResource(R.mipmap.sex_red);
                }
                if (!TextUtils.isEmpty(listBean.getBirthday())) {
                    String substring = listBean.getBirthday().substring(0, 4);
                    String time = Utils.getStringTime(new Date());
                    int age = (Integer.parseInt(time)) - (Integer.parseInt(substring));
                    viewHolder1.tvAge.setText(age + "");
                }
                viewHolder1.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemSetClick.setItemClick(viewHolder1.itemView, listBean);
                    }
                });
                viewHolder1.tvNikeName.setText(listBean.getNickName());
                viewHolder1.linearLike.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemSetClick.setLikeClick(v, listBean);
                    }
                });
                viewHolder1.imageIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemSetClick.setIconClick(v, listBean);
                    }
                });
                int finalPosition = position;
                viewHolder1.linearSendVoice.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemSetClick.setPlayVoiceClick(listBean, viewHolder1.imageSendVoiceIcon, finalPosition, viewHolder1.imagePlay);
                    }
                });
                viewHolder1.linearShare.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemSetClick.setItemClickShare(v, listBean);
                    }
                });
            }
        }
    }


    @Override
    public int getItemViewType(int position) {
        if (flag.equals("cummunity") && position == 2) {
           /* if (tlist.size() <= 2 && position == tlist.size()) {
                return BANNER;
            } else if (position == 2) {
                return BANNER;
            }*/
            return BANNER;
        } else {
            return ITEMTYPE;
        }
    }

    @Override
    public int getItemCount() {
        int count = tlist == null ? 0 : tlist.size();
        if(flag.equals("cummunity")){
            count = count+1;
        }
       return count;
    }

    /**
     * @return
     * @method
     * @description 查询帖子详情
     * @date: 2018/12/14 14:29
     * @author: ljp
     */
    private void setHttpPost(String hotId) {
        CommunityService.selectDynamic(CommunityFragment.mySeleInfo.getToken(),
                PhoneUtils.getDeviceInfo(context), CommunityFragment.mySeleInfo.getId(), hotId).subscribe(postBean -> {
            Log.i(TAG, "setHttpPost: -----------" + postBean.getCode());
            Log.i(TAG, "setHttpPost: -----------" + postBean.toString());
            if (postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                PostBean.ObjectBean objectBean = postBean.getObjectBean();
                PostBean.PageBean.ListBean listBean = new PostBean.PageBean.ListBean(objectBean.getId(), objectBean.isNewRecord(),
                        objectBean.getMdTitle(), objectBean.getContent(), objectBean.getMdUpdateDate(), objectBean.getUserId(),
                        objectBean.getAvatarUrl(), objectBean.getNickName(), objectBean.getGender(), objectBean.getBirthday(),
                        objectBean.getFabulousCount(), objectBean.getDiscussCount(), objectBean.getIsFabulous(), objectBean.getvType(),
                        objectBean.getuType(), objectBean.getUrl(), objectBean.getWarrant(), objectBean.getIsFollow(), objectBean.getVoiceUrl(), objectBean.getDuration());
                Intent intent = new Intent(context, PostDetailsActivity.class);
                intent.putExtra("listBean", listBean);
                context.startActivity(intent);
            }
        }, throwable -> {
            Utils.toast_MakeText(context.getResources().getString(R.string.net_error), context);
        });
    }
    /**
     * 头布局
     */
    class HeadViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.banner_list)
        BannerLayout bannerList;
        View view;

        public HeadViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            ButterKnife.bind(this, itemView);
        }
    }

    /**
     * 布局1
     */
    class ViewHolder1 extends RecyclerView.ViewHolder {
        //@BindView(R.id.circle_picture)
        //CircleImageView circlePicture;
        // @BindView(R.id.tv_title)
        // TextView tvTitle;
        @BindView(R.id.tv_content)
        TextView tvContent;
        @BindView(R.id.image_icon)
        CircleImageView imageIcon;
        @BindView(R.id.tv_nike_name)
        TextView tvNikeName;
        @BindView(R.id.tv_comm_number)
        TextView tvCommNumber;
        @BindView(R.id.tv_like_number)
        TextView tvLikeNumber;
        @BindView(R.id.tv_date)
        TextView tvDate;
        @BindView(R.id.image_isanchor)
        ImageView imageIsanchor;
        @BindView(R.id.image_vip)
        ImageView imageVip;
        @BindView(R.id.image_like)
        ImageView imageLike;
        @BindView(R.id.linear_like)
        LinearLayout linearLike;
        @BindView(R.id.image_sex)
        ImageView imageSex;
        @BindView(R.id.tv_age)
        TextView tvAge;
        @BindView(R.id.linear_sex_age)
        LinearLayout linearSexAge;
        @BindView(R.id.linear_share)
        LinearLayout linearShare;
        View itemView;
        @BindView(R.id.image_send_voice_icon)
        ImageView imageSendVoiceIcon;
        @BindView(R.id.image_play)
        ImageView imagePlay;
        @BindView(R.id.tv_voice_time)
        TextView tvVoiceTime;
        @BindView(R.id.linear_send_voice)
        RelativeLayout linearSendVoice;
        @BindView(R.id.recycler_picture)
        RecyclerView recyclerPostPicture;

        public ViewHolder1(View itemView) {
            super(itemView);
            this.itemView = itemView;
            ButterKnife.bind(this, itemView);
        }
    }

    public interface ItemSetClick {
        void setIconClick(View view, PostBean.PageBean.ListBean listBean);

        void setIconClick(View view, CommBean.MapBean.DynamicBean dynamic);

        void setItemClick(View view, PostBean.PageBean.ListBean listBean);

        void setLikeClick(View view, CommBean.MapBean.DynamicBean dynamic);

        void setLikeClick(View view, PostBean.PageBean.ListBean listBean);

        void setItemClick(View view, CommBean.MapBean.DynamicBean dynamic);

        void setNoticeClick(View view, List<CoummunityNotice.PageBean.ListBean> notices);

        void setPlayVoiceClick(PostBean.PageBean.ListBean listBean, View view, int position, View viewPlay);

        void setPlayVoiceClick(CommBean.MapBean.DynamicBean dynamic, View view, int position);

        //分享
        void setItemClickShare(View view, PostBean.PageBean.ListBean listBean);

    }
}
